'use strict';

const { logger } = require('ee-core/log');
const { BasedbService } = require('./basedb');

/**
 * sqlite数据存储
 * @class
 */
class DbService extends BasedbService {
    
    constructor () {
        const options = {
            dbname: 'sqlite-demo.db',
        }
        super(options);
        this.userTableName = 'user';
    }

    /*
     * 初始化
     */
    init() {
        // 初始化数据库
        this._init();

        // 检查表是否存在
        const masterStmt = this.db.prepare('SELECT * FROM sqlite_master WHERE type=? AND name = ?');
        let tableExists = masterStmt.get('table', this.userTableName);
        if (!tableExists) {
            // 创建表
            const create_user_table_sql =
            `CREATE TABLE ${this.userTableName}
            (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name CHAR(50) NOT NULL,
                age INT
            );`
            this.db.exec(create_user_table_sql);
        }
    }

    /*
     * 增 Test data (sqlite)
     */
    async insert(data) {
        const insert = this.db.prepare(`INSERT INTO ${this.userTableName} (name, age) VALUES (@name, @age)`);
        insert.run(data);
        return true;
    }

    /*
     * 删 Test data (sqlite)
     */
    async delete(name = '') {
        const delUser = this.db.prepare(`DELETE FROM ${this.userTableName} WHERE name = ?`);
        delUser.run(name);
        return true;
    }

    /*
     * 改 Test data (sqlite)
     */
    async update(name = '', age = 0) {
        const updateUser = this.db.prepare(`UPDATE ${this.userTableName} SET age = ? WHERE name = ?`);
        updateUser.run(age, name);
        return true;
    }  

    /*
     * 查 Test data (sqlite)
     */
    async get(name = '', age = 0) {
        logger.info('get name: {}, age: {}', name, age);
        const selectUser = this.db.prepare(`SELECT * FROM ${this.userTableName} WHERE name = @name or age = @age`);
        const users = selectUser.all({name: name, age: age});
        return users;
    }
  
    /*
     * all Test data (sqlite)
     */
    async getAll() {
        const selectAllUser = this.db.prepare(`SELECT * FROM ${this.userTableName} `);
        const allUser =  selectAllUser.all();
        return allUser;
    }

}
DbService.toString = () => '[class DbService]';

module.exports = {
    DbService,
    dbService: new DbService()
};